//
//  WebServiceManager.m
//  smarthings
//
//  Created by Stefan Tsvyatkov on 10/20/14.
//  Copyright (c) 2014 Stefan Tsvyatkov. All rights reserved.
//

#import "SMTWebServiceManager.h"
#import <AFNetworking.h>

NSString * const kBaseURLKey = @"SMTBaseServerURL";

@interface SMTWebServiceManager ()

@property(strong,nonatomic) AFHTTPSessionManager * sessionManager;

- (void)refreshSessionManager;

@end

@implementation SMTWebServiceManager

+ (SMTWebServiceManager *)sharedInstance {
    static dispatch_once_t onceToken;
    static SMTWebServiceManager *sharedInstance = nil;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[SMTWebServiceManager alloc] init];
    });
    return sharedInstance;
}

- (id)init {
    self = [super init];
    if (self) {
        [self refreshSessionManager];
    }
    return self;
}

- (void)refreshSessionManager {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.HTTPAdditionalHeaders = @{@"Content-Type": @"application/json", @"Accept": @"application/json"};
    _sessionManager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:self.baseServerURL] sessionConfiguration:configuration];
    _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
}

- (NSString *)baseServerURL {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![defaults objectForKey:kBaseURLKey]) {
        [defaults setObject:@"http://tsvyatkov.eu:1515/services/" forKey:kBaseURLKey];
        [defaults synchronize];
    }
    return [defaults objectForKey:kBaseURLKey];
}

- (void)setBaseServerURL:(NSString *)baseServerURL {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:baseServerURL forKey:kBaseURLKey];
    [defaults synchronize];
    [self refreshSessionManager];
}

#pragma mark - Interface methods

- (void)getThingsList:(SuccessResponseBlock)success
              failure:(FailureResponseBlock)failure {
    [self.sessionManager GET:@"things" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}

- (void)getAttributesForHref:(NSString *)href
                     success:(SuccessResponseBlock)success
                     failure:(FailureResponseBlock)failure {
    [self.sessionManager GET:href parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}

- (void)getThingPropertyTypesList:(SuccessResponseBlock)success
                          failure:(FailureResponseBlock)failure {
    [self.sessionManager GET:@"things/metadata/properties" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}

- (void)getThingActionTypesList:(SuccessResponseBlock)success
                        failure:(FailureResponseBlock)failure {
    [self.sessionManager GET:@"things/metadata/actions" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}

- (void)addThing:(NSDictionary *)thing
         success:(SuccessResponseBlock)success
         failure:(FailureResponseBlock)failure {
    [self.sessionManager POST:@"things/registrations" parameters:thing success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}

- (void)deleteThing:(NSString *)thingUUID
            success:(SuccessResponseBlock)success
            failure:(FailureResponseBlock)failure {
    [self.sessionManager DELETE:[NSString stringWithFormat:@"things/registrations/%@", thingUUID] parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}

- (void)executeAction:(NSString *)href
              success:(SuccessResponseBlock)success
              failure:(FailureResponseBlock)failure {
    [self.sessionManager POST:href parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        success(responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        failure(error);
    }];
}

- (void)getPropertyValue:(NSString *)href
                 success:(SuccessResponseBlock)success
                 failure:(FailureResponseBlock)failure {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:[NSString stringWithFormat:@"%@%@", self.baseServerURL, href] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (operation.response.statusCode == 204) {
            failure(nil);
        }
        else {
            success(operation.responseString);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        failure(error);
    }];
}


@end
